package Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Observable;

public class NetworkHandler extends Observable implements Runnable {

	private Socket client;
	private ArrayList<Socket> clientSocket;
	private ServerSocket serverSocket;

	private PrintWriter writer;
	private BufferedReader reader;

	private String message = "";

	private String serverIp;

	private String teamName = "red";

	private boolean isServer = false;
	private boolean stop = false;

	public NetworkHandler(){
		clientSocket = new ArrayList<Socket>();
	}
	
	public void setServer(boolean b) {
		this.isServer = b;
	}

	public void setServerIp(String text) {
		this.serverIp = text;
	}

	@Override
	public void run() {
			if (isServer) {
				startServer();
			} else {
				startClient();
			}
	}

	private void startClient() {
		try {
			client = new Socket(serverIp, 2004);
			writer = new PrintWriter(new OutputStreamWriter(
					client.getOutputStream()));
			reader = new BufferedReader(new InputStreamReader(
					client.getInputStream()));
		} catch (Exception e){
			System.out.println("Client error");
		}
		while(!stop){
		try {
			Thread.sleep(100);	
			if(!message.isEmpty()){
				writeMessage(message,client);
				message ="";
			}
			if(reader.ready()){
				message = reader.readLine();
				System.out.println(message);
				//output = antwort vom server;
				modified();
				//TODO: Remove message = "";!
				//message = "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		}
	}

	private void startServer() {
		String msg;
		try{
		serverSocket = new ServerSocket(2004);
		serverSocket.setSoTimeout(100);
		}catch(Exception e){}
		while(!stop){
			try {
				if(clientSocket.add(serverSocket.accept()))
					System.out.println("Client "+clientSocket.get(clientSocket.size()-1)+" connected!");
			} catch(Exception e){}
			try {
				for(Socket client : clientSocket){
					msg = readMessage(client);
					if(!msg.isEmpty())
						if(!msg.equals("Bye.")){
							message = msg;
							System.out.println("client > "+message);
							modified();
						} else {
							//beenden
						}
							
				}
				for(Socket client : clientSocket){
					if(!message.isEmpty())
						writeMessage(message, client);
				}
				message = "";				
	
			} catch (IOException ex) {
				System.out.println("Provider - IOException: " + ex.getMessage());
			}
		}
	}

	private void writeMessage(String msg, Socket client) throws IOException {
		writer = new PrintWriter(new OutputStreamWriter(
				client.getOutputStream()));
		if (isServer) {
			writer.println(msg);
		} else {
			writer.println(teamName + "-" + msg);
		}
		writer.flush();
		System.out
				.println("sent " + (isServer ? "server> " : "client> ") + msg);
	}

	private String readMessage(Socket client) throws IOException {
		String msg = "";
		reader = new BufferedReader(new InputStreamReader(
				client.getInputStream()));
		if (reader.ready()) {
			msg = reader.readLine();
		}
		return msg;
	}

	public void setGame(String newGame) {
		message = newGame;
	}

	public void modified() {
		setChanged();
		notifyObservers(message);
		message = "";
	}

	public void sendMessage(String s) {
		message = s;
		//if(message.equalsIgnoreCase("bierdeckel"))
		//System.out.println("setMessage: " + message);
		//modified();
	}

	public String getMessage() {
		return message;
	}

	public String getTeamName() {
		return teamName;
	}

	public void setTeamName(String teamName) {
		this.teamName = teamName;
	}
}
